<template>
  <div>
    <el-card class="users_main">
      <!-- 顶部搜索 -->
      <HeadAdd :addText="'新增'" :addTitle="'用户'" @addClick="showDialogClick">
        <template #search>
          <HeadSearch
            :searchText="query"
            @search="getUsersList"
            @clear="getUsersList"
          />
        </template>
      </HeadAdd>
      <!-- 警告框 -->
      <el-alert
        :title="`共 ${total} 条记录`"
        type="info"
        show-icon
        :closable="false"
        class="alert"
      >
      </el-alert>
      <!-- 表格区域 -->
      <el-table :data="usersList" v-loading="loading" style="width: 100%">
        <el-table-column
          align="center"
          prop="id"
          label="序号"
          style="width: 15%"
        />
        <el-table-column
          align="center"
          prop="email"
          label="邮箱"
          style="width: 15%"
        />
        <el-table-column
          align="left"
          prop="phone"
          label="联系电话"
          style="width: 15%"
        />
        <el-table-column
          align="center"
          prop="username"
          label="用户名"
          style="width: 15%"
        />
        <el-table-column
          align="center"
          prop="permission_group_title"
          label="权限组名称"
          style="width: 15%"
        />
        <el-table-column
          align="center"
          prop="role"
          label="角色"
          style="width: 15%"
        />
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              plain
              circle
              @click="showDialogClick('编辑', row.id)"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              plain
              circle
              v-if="row.id !== 2"
              @click="delUser(row.id)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <FootPage :current="query" :total="total" @getList="getUsersList" />
    </el-card>
    <!-- 弹出对话框 -->
    <el-dialog
      :title="`${text}用户`"
      :visible.sync="showDialog"
      v-loading="dialogLoaging"
      @close="btnCancel"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="password">
          <el-input v-model="ruleForm.password" />
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="ruleForm.role" />
        </el-form-item>
        <el-form-item label="权限组名称" prop="permission_group_id">
          <el-select v-model="ruleForm.permission_group_id">
            <el-option
              v-for="item in permissionSimple"
              :key="item.key"
              :value="item.id"
              :label="item.title"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="ruleForm.phone" />
        </el-form-item>
        <el-form-item label="介绍">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="Please input"
            v-model="ruleForm.introduction"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        style="width: 400px; margin: 0 auto; text-align: center"
      >
        <el-button @click="btnCancel">取消</el-button>
        <el-button type="primary" @click="btnOk">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 封装函数
import { required } from '@/module-manage/utils/index.js'
// 调用组件
import HeadAdd from '@/module-manage/components/head-add'
import HeadSearch from '@/module-manage/components/head-search'
import FootPage from '@/module-manage/components/foot_page'
// 请求接口
import { list, remove, detail, update, add } from '@/api/base/users.js'
import { simple } from '@/api/base/permissions.js'
export default {
  name: 'Users',
  components: { HeadAdd, HeadSearch, FootPage },
  data () {
    return {
      // 获取用户列表时的参数
      query: {
        page: 1, // 当前所处的页
        pagesize: 10, // 每页显示的条数
        username: '' // 搜索时用户名
      },
      total: 0, // 用户列表总数
      usersList: [], // 用户列表
      loading: false,
      showDialog: false,
      text: '', // 对话框提示文本
      // 表单数据
      ruleForm: {
        avatar: '', // 头像
        id: '',
        username: '', // 用户名
        email: '', // 邮箱
        password: '', // 密码
        role: '', // 角色
        permission_group_id: '', // 权限组名称
        phone: '', // 联系电话
        introduction: '' // 介绍
      },
      rules: {
        username: [required('用户名')],
        password: [
          required('密码'),
          { min: 6, max: 16, message: '长度在6到16个字符', trigger: 'blur' }
        ],
        email: [
          required('邮箱'),
          {
            pattern: /^[0-9a-zA-Z]{1,20}@[0-9a-zA-Z]{1,6}.[0-9a-zA-Z]{1,6}$/,
            message: '邮箱格式不正确',
            trigger: 'blur'
          }
        ],
        permission_group_id: [required('权限组名称')],
        phone: [
          {
            pattern: /^1[0-9]{10}$/,
            message: '联系电话格式不正确',
            trigger: 'blur'
          }
        ]
      },
      permissionSimple: [], // 权限组名称
      dialogLoaging: false,
      password: true
    }
  },
  created () {
    this.getUsersList()
  },
  methods: {
    // 获取用户列表
    async getUsersList () {
      this.loading = true
      try {
        const { data } = await list(this.query)
        this.usersList = data.list
        this.total = data.counts
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    },
    // 删除用户
    delUser (id) {
      this.$confirm('此操作将永久删除用户 , 是否继续?')
        .then(async () => {
          await remove({ id: id })
          this.$message.success('删除用户成功')
          this.getUsersList()
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 点击添加或编辑弹出对话框
    async showDialogClick (text, id) {
      this.dialogLoaging = true
      this.text = text
      if (id) {
        this.password = false
        const { data } = await detail({ id: id })
        this.ruleForm = data
      }
      const res = await simple()
      this.permissionSimple = res.data
      this.showDialog = true
      this.dialogLoaging = false
    },
    // 关闭对话框
    btnCancel () {
      this.showDialog = false
      this.password = true
      this.$refs.ruleForm.resetFields()
      this.ruleForm = {
        avatar: '',
        id: '',
        username: '',
        email: '',
        password: '',
        role: '',
        permission_group_id: '',
        phone: '',
        introduction: ''
      }
    },
    // 提交
    async btnOk () {
      await this.$refs.ruleForm.validate()
      const data = {
        avatar: this.ruleForm.avatar,
        email: this.ruleForm.email,
        introduction: this.ruleForm.introduction,
        permission_group_id: this.ruleForm.permission_group_id,
        phone: this.ruleForm.phone,
        role: this.ruleForm.role,
        username: this.ruleForm.username
      }
      if (this.ruleForm.id !== '') {
        await update({
          ...data,
          id: this.ruleForm.id
        })
        this.$message.success('编辑用户成功')
      } else {
        await add({
          ...data,
          password: this.ruleForm.password,
          sex: ''
        })
        this.$message.success('创建用户成功')
      }
      this.getUsersList()
      this.btnCancel()
    }
  }
}
</script>

<style scoped lang="less">
.users_main {
  margin: 20px;
  // 警告框
  .alert {
    margin-bottom: 15px;
  }
}
</style>
